const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class WallsHandler extends BaseHandler {

    get pattern() {
        return '/me/walls';
    }

    doGET(request, response) {
        if(!request.session.user.authenticated && !request.query.identifier) {
            response.end(JSON.stringify([]));
        } else {
            var userId = request.session.user.id;
            if(request.query.identifier) {
                this.Controller.getWallsByUserIdentifier(request.query.identifier, (data) => {
                    response.end(JSON.stringify(data));
                });
            } else {
                this.Controller.getWallsByUserId(userId, (data) => {
                    response.end(JSON.stringify(data));
                });
            }
        }
    }

    doPOST(request, response) {
        
        if(!request.session.user.authenticated && !request.session.is_wechat) {
            response.redirect('/login');
        } else {
            if (!request.session.is_wechat) {
                request.body.user_id = request.session.user.id;
            }
            //TODO: Check if the user has permission to save/update wall
            let data = request.body;
            
            data.sources = (data.sources && typeof data.sources === 'object' && data.sources) || (data.sources && typeof data.sources === 'string' && JSON.parse(data.sources));
            this.Controller.saveOrUpdateWall(data, (data) => {
                if (request.is_ajax) {
                    response.json(data);
                } else {
                    response.redirect('/console');
                }
            });
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.POST, this.doPOST);
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = WallsHandler;